
import AdManager, { Platform } from "../../Platforms/AdManager";
import AdapterManager, { AdaptaterType } from "../../UIFrame/AdapterManager";
import { FormType } from "../../UIFrame/config/SysDefine";
import UIBase from "../../UIFrame/UIBase";

const { ccclass, property } = cc._decorator;

@ccclass
export default class NativeInsert extends UIBase {

    formType = FormType.TopTips;
    static prefabPath = "prefabs/UIForms/ad/NativeInsert";

    private adData: any;

    onShow(data) {
        this.adData = data;
        this.initUI(data);
    }

    private eventShow = () => {
        console.log('EVENT_SHOW');
        if (this.node.active) {
            AdManager.getInstance().onNativeReportAdShow(this.adData.adId);
        }
    };

    start() {
        AdapterManager.getInstanse.adapatByType(AdaptaterType.Center, this.node, 0);

        if (AdManager.getInstance().platform == Platform.huawei_H5) {
            window["qg"].onShow(() => {
                console.log("切回后台再切回来上报事件监听");
                this.eventShow();
            });
        }
    }

    initUI(_res) {
        this.node.getChildByName('adLittle').getComponent('cc.Label').string = _res.title;
        this.node.getChildByName('adDesc').getComponent('cc.Label').string = _res.desc || _res.source;//华为渠道的字段不一样
        this.node.getChildByName('button').getChildByName('Label').getComponent('cc.Label').string = _res.clickBtnTxt;

        let str = _res.imgUrlList[0];
        cc.loader.load(str, function (err, texture) {
            this.node.getChildByName('adSprite').getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture);
        }.bind(this));

        this.node.getChildByName('adSprite').on(cc.Node.EventType.TOUCH_START, this.nativeInsertClick, this);
        this.node.getChildByName('button').on(cc.Node.EventType.TOUCH_START, this.nativeInsertClick, this);
        this.node.getChildByName('btn_close').on(cc.Node.EventType.TOUCH_START, this.nativeaInsertClose, this);
    }

    nativeInsertClick() {
        AdManager.getInstance().onNativeAdClick(this.adData.adId);
    }

    nativeaInsertClose() {
        this.closeUIForm();

        //设置关闭广告 的openidKey
        AdManager.getInstance().adMGBackend.adClose(this.adData.openIdKey);
    }
}
